package cn.jhc.servlet;



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oracle.webservices.internal.api.EnvelopeStyle.Style;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * Servlet implementation class Code
 */
@WebServlet("/Vcode")
public class Code extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String[] strings = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","P","R","S","T","U","V","W","X","Y","Z"};
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/png");
		
		String relNum = getVcodeNum();
		request.getSession().setAttribute("relNum", relNum);
	        
		BufferedImage bufferedImage = new BufferedImage(120,40, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = bufferedImage.createGraphics();
		graphics.setFont(new Font(null, Font.BOLD, 24));
		graphics.setColor(getRandomColor());
		graphics.drawString(relNum,20,30);
		
		setOoO(graphics);
		ImageIO.write(bufferedImage, "png", response.getOutputStream());
	}
	
	
	//为了生成  随机验证码的方法
	private String getVcodeNum() {
		//为了生成  随机验证码的字符集
				String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
			        char[] rands = new char[4];
			        for (int i = 0; i < 4; i++) {
			            int rand = (int) (Math.random() * 62);
			            rands[i] = chars.charAt(rand);
			        }
			    //将int类型的rands  转化成  string 类型
				String rel = String.valueOf(rands);
				return rel;
	}
	
	//生成随机的小点点
	private void setOoO(Graphics2D graphics2d) {
		for(int i = 0; i < 200;i++) {
			int x = (int) (Math.random() * 120);
			int y = (int) (Math.random() * 40);		
			graphics2d.setColor(getRandomColor());
			graphics2d.drawOval(x, y, 1, 0);
		}
	}
	
	//生成随机颜色
	private Color getRandomColor() {
		Color color = null;
		int red = (int) (Math.random() * 255);
		int green = (int) (Math.random() * 255);
		int blue = (int) (Math.random() * 255);
		color = new Color(red, green, blue);
		return color;
	}

}

